package com.Blog.www.filter;

import com.Blog.www.constant.DataConstant;
import com.Blog.www.constant.PageConstant;
import com.Blog.www.constant.TipsConstant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 各种界面的登录过滤器
 *
 * @author 君未洋
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String contextPath = request.getContextPath();
        //获取资源请求路径
        String uri = request.getRequestURI();
        //判断是否包含登录相关资源,还有css, js 图片,验证码等资源
        if (uri.contains("/login.jsp") || uri.contains("/User/loginServlet") || uri.contains("/css/") || uri.contains("/js/") ||
                uri.contains("/fonts/") || uri.contains("/User/checkCode") || uri.contains("/index.jsp") || uri.contains("/User/login")
                || uri.contains("/User/regist") || uri.contains("/User/recall") || uri.contains("/regist.jsp") || uri.contains("/recall.jsp")
                || uri.contains("/User/touristLogin") || uri.contains("/User/autoLogin")) {
            //直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //不包含user这个数据的就识别为未登录状态
            Object user = request.getSession().getAttribute(DataConstant.USER_A);
            if (user != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                request.setAttribute(PageConstant.USER_C, TipsConstant.USER_LOGIN_A);
                request.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
